<template>
  <div class="input-msg"
       ref="msg"
       contenteditable=""
       @input="changeText"
	   @focus="focus"
	   @click="$emit('click')"
	   @blur="blur"
	   ></div>
</template>
 
<script>
function createNode(txt) {
  const template = `${txt}`;
  let tempNode = document.createElement('div');
  tempNode.innerHTML = template;
  return tempNode.firstChild;
 }


export default {
  name: 'editDiv',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data(){
	  return {
		  lastNode:'', lastOffset:0,
	  }
  },
  watch: {
    value(newvalue, oldvalue) {
		console.log("aaaa")
		this.$refs.msg.innerHTML = newvalue;
    }
  },
  methods: {
	  
	  blur(){
		  this.lastNode = getSelection().anchorNode
		  this.lastOffset = getSelection().anchorOffset
	  },
	  focus(){
		  this.$emit('focus')
	  },
	  content(){
		  return this.$refs.msg.innerHTML;
	  },
	  
	  clear(){
		  this.$refs.msg.innerHTML = '';
	  },
	  
	insert(fragment){
		const node = createNode(fragment)
		
		console.log("node",getSelection().anchorNode, getSelection().anchorOffset)
		this.$refs.msg.insertAfter(node, getSelection().anchorNode)
		getSelection().setPosition(node, 1)
		console.log("inserted", getSelection().anchorNode);
		// this.$refs.msg.innerHTML = this.$refs.msg.innerHTML.slice(0, pos) + fragment + this.$refs.msg.innerHTML.slice(pos)
	},
	
	
    changeText(event) {
	console.log(window.getSelection())
      this.$emit('input', this.$el.innerHTML);
    },
 
    // keepLastIndex(obj) {
    //   if (window.getSelection) {
    //     //ie11 10 9 ff safari
    //     obj.focus(); //解决ff不获取焦点无法定位问题
    //     var range = window.getSelection(); //创建range
    //     range.selectAllChildren(obj); //range 选择obj下所有子内容
    //     range.collapseToEnd(); //光标移至最后
    //   } else if (document.selection) {
    //     //ie10 9 8 7 6 5
    //     var range = document.selection.createRange(); //创建选择对象
    //     //var range = document.body.createTextRange();
    //     range.moveToElementText(obj); //range定位到obj
    //     // range.collapse(false); //光标移至最后
    //     range.select();
    //   }
    // }
  }
};
</script>
 
<style scoped>
.input-msg {
  border: none;
  display: block;
  overflow-y: scroll;
  overflow-x: hidden;
  background-color: white;
  padding: 0.25em 0.5em;
  user-select: all;
  border-radius: 0.5em;
  min-height: 1em;
}
 
.input-msg:focus {
  border: 0;
  outline: 0;
}
 
.input-msg:empty:before {
  content: '';
}
</style>